package com.paziy.jan.thread;

import java.util.LinkedList;

public class Buffer<E> {

    private LinkedList<E> bufferData;

    private boolean isClosed = true;

    public Buffer() {
        this(new LinkedList<E>());
    }

    public Buffer(LinkedList<E> bufferData) {
        this.bufferData = bufferData;
    }

    public boolean isClosed() {
        return isClosed;
    }

    public synchronized void open() {
        isClosed = false;

    }

    public synchronized void close() {
        isClosed = true;
        notifyAll();
    }

    public synchronized E peek() {

        while (bufferData.isEmpty() && !isClosed) {
            try {
                wait();
            } catch (InterruptedException e) {
                //todo InterruptedException
            }
        }

        //if (bufferData.isEmpty() && isClosed) return null;//индекатор конца буфера

        return bufferData.peek();
    }

    public synchronized E pop() {

        while(bufferData.isEmpty() && !isClosed) {
            try {
                wait();
            } catch (InterruptedException e) {
                //todo InterruptedException
            }
        }

        if (bufferData.isEmpty() && isClosed) return null;//индекатор конца буфера

        return bufferData.pop();
    }

    public synchronized Boolean push(E element) {

        if (isClosed) {
            return false;
        } else {
            bufferData.push(element);

            notify();
            return true;
        }
    }
}
